﻿using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using SearchForWorkitemsChanges.ExternalActions;
using System.Collections.Generic;
using System.Configuration;

namespace SearchForWorkitemsChanges
{
    /// <summary>
    /// The Instance resolver used to retrieve all instance of <see cref="IExternalAction"/>.
    /// </summary>
    /// <seealso cref="IExternalAction" />
    internal static class ObjectResolver
    {
        //public static T ExternalActionsResolve<T>()
        //where T : class
        //{
        //    return container.Resolve<T>();
        //}

        /// <summary>
        /// Get all instances of <see cref="IExternalAction"/>.
        /// </summary>
        /// <returns>An <see cref="IEnumerable{T}"/> where T is <see cref="IExternalAction"/></returns>
        /// <seealso cref="IExternalAction" />
        public static IEnumerable<IExternalAction> ExternalActionsResolveAll()
        {
            return CurrentContainer.ResolveAll<IExternalAction>();
        }

        /// <summary>
        /// Multi thread locker for instance creation
        /// </summary>
        private static readonly object locker = new object();
        private static IUnityContainer container;

        /// <summary>
        /// Gets the current container.
        /// </summary>
        /// <value>
        /// The current container.
        /// </value>
        private static IUnityContainer CurrentContainer
        {
            get 
            {
                if(container == null)
                    lock(locker)
                        if (container == null) 
                        {
                            InitializeContainer();
                        }
                return container;
            }
        }

        /// <summary>
        /// Initializes the <see cref="UnityContainer"/> container.
        /// </summary>
        private static void InitializeContainer()
        {
            var ctx = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(ctx, section, "ExternalActions");

            container = ctx;
        }
    }
}
